<template>
  <div class="backup-restore-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">数据备份与还原</div>
      <div class="header-actions">
        <el-button type="primary" @click="createBackup">创建备份</el-button>
      </div>
    </div>

    <!-- 备份配置 -->
    <el-card shadow="hover" class="backup-config-card">
      <template #header>
        <div class="card-header">
          <span>备份配置</span>
        </div>
      </template>
      
      <el-form :model="backupConfig" label-width="120px">
        <el-form-item label="自动备份">
          <el-switch v-model="backupConfig.autoBackup"></el-switch>
        </el-form-item>
        
        <template v-if="backupConfig.autoBackup">
          <el-form-item label="备份周期">
            <el-select v-model="backupConfig.backupFrequency" style="width: 100%">
              <el-option label="每天" value="daily"></el-option>
              <el-option label="每周" value="weekly"></el-option>
              <el-option label="每月" value="monthly"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="备份时间">
            <el-time-picker v-model="backupConfig.backupTime" format="HH:mm" style="width: 100%"></el-time-picker>
          </el-form-item>
        </template>
        
        <el-form-item label="保留备份数量">
          <el-input-number v-model="backupConfig.keepBackups" :min="1" :max="100"></el-input-number>
        </el-form-item>
        
        <el-form-item label="备份内容">
          <el-checkbox-group v-model="backupConfig.backupContent">
            <el-checkbox label="database">数据库</el-checkbox>
            <el-checkbox label="models">模型文件</el-checkbox>
            <el-checkbox label="config">系统配置</el-checkbox>
            <el-checkbox label="logs">系统日志</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveBackupConfig">保存配置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 备份列表 -->
    <el-card shadow="hover" class="backup-list-card">
      <template #header>
        <div class="card-header">
          <span>备份列表</span>
          <div class="header-actions">
            <el-button size="small" type="primary" @click="refreshBackupList">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="backupList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="name" label="备份名称" min-width="200"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="size" label="大小" width="120"></el-table-column>
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-tag 
              :type="getBackupTypeTag(scope.row.type)" 
              effect="plain"
            >
              {{ getBackupTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'success' ? 'success' : scope.row.status === 'failed' ? 'danger' : 'info'"
            >
              {{ scope.row.status === 'success' ? '成功' : scope.row.status === 'failed' ? '失败' : '进行中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="downloadBackup(scope.row)" :disabled="scope.row.status !== 'success'">下载</el-button>
            <el-button size="small" type="success" @click="restoreBackup(scope.row)" :disabled="scope.row.status !== 'success'">还原</el-button>
            <el-button size="small" type="danger" @click="deleteBackup(scope.row)" :disabled="scope.row.status === 'processing'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 数据还原区域 -->
    <el-card shadow="hover" class="restore-card">
      <template #header>
        <div class="card-header">
          <span>数据还原</span>
        </div>
      </template>
      
      <div class="upload-area">
        <el-upload
          class="upload-component"
          drag
          action="#"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          :limit="1"
          accept=".zip,.sql,.bak"
        >
          <el-icon class="el-icon-upload"><i class="el-icon-upload"></i></el-icon>
          <div class="upload-text">将备份文件拖到此处，或<em>点击上传</em></div>
          <div class="upload-hint">支持 .zip, .sql, .bak 格式</div>
        </el-upload>
      </div>
      
      <div class="restore-actions">
        <el-button type="warning" @click="restoreFromFile" :disabled="!selectedFile">从文件还原</el-button>
        <el-checkbox v-model="restoreConfig.clearBeforeRestore">还原前清空数据</el-checkbox>
      </div>
    </el-card>

    <!-- 创建备份对话框 -->
    <el-dialog 
      v-model="backupDialogVisible" 
      title="创建备份"
      width="500px"
      destroy-on-close
    >
      <el-form :model="newBackupForm" label-width="120px">
        <el-form-item label="备份名称" prop="name">
          <el-input v-model="newBackupForm.name" placeholder="请输入备份名称"></el-input>
        </el-form-item>
        
        <el-form-item label="备份内容">
          <el-checkbox-group v-model="newBackupForm.content">
            <el-checkbox label="database">数据库</el-checkbox>
            <el-checkbox label="models">模型文件</el-checkbox>
            <el-checkbox label="config">系统配置</el-checkbox>
            <el-checkbox label="logs">系统日志</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="备份描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="newBackupForm.description" 
            rows="3"
            placeholder="请输入备份描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="backupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreateBackup">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 还原确认对话框 -->
    <el-dialog 
      v-model="restoreDialogVisible" 
      title="确认还原" 
      width="500px"
    >
      <div class="restore-warning">
        <el-alert
          title="警告：数据还原操作不可逆"
          type="warning"
          description="还原操作将覆盖当前系统数据，建议在操作前先创建备份。"
          show-icon
          :closable="false"
        ></el-alert>
        <div class="restore-detail">
          <p><strong>备份名称：</strong>{{ currentBackup.name }}</p>
          <p><strong>创建时间：</strong>{{ currentBackup.createdAt }}</p>
          <p><strong>包含内容：</strong>{{ getBackupContent(currentBackup) }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="restoreDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmRestore">确定还原</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)

// 备份配置
const backupConfig = reactive({
  autoBackup: true,
  backupFrequency: 'daily',
  backupTime: new Date(2023, 0, 1, 3, 0), // 凌晨3点
  keepBackups: 10,
  backupContent: ['database', 'models', 'config']
})

// 备份列表
const backupList = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 还原配置
const restoreConfig = reactive({
  clearBeforeRestore: true
})

// 选中的文件
const selectedFile = ref(null)

// 对话框控制
const backupDialogVisible = ref(false)
const restoreDialogVisible = ref(false)

// 新建备份表单
const newBackupForm = reactive({
  name: '',
  content: ['database'],
  description: ''
})

// 当前备份对象
const currentBackup = reactive({
  id: '',
  name: '',
  createdAt: '',
  content: []
})

// 获取备份列表
const fetchBackupList = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 模拟备份数据
    const mockData = [
      {
        id: '1',
        name: '每日自动备份-20230615',
        createdAt: '2023-06-15 03:00:00',
        size: '125.6 MB',
        type: 'auto',
        status: 'success',
        content: ['database', 'config']
      },
      {
        id: '2',
        name: '每日自动备份-20230614',
        createdAt: '2023-06-14 03:00:00',
        size: '123.2 MB',
        type: 'auto',
        status: 'success',
        content: ['database', 'config']
      },
      {
        id: '3',
        name: '模型更新前备份',
        createdAt: '2023-06-13 14:32:18',
        size: '321.5 MB',
        type: 'manual',
        status: 'success',
        content: ['database', 'models', 'config']
      },
      {
        id: '4',
        name: '系统升级前完整备份',
        createdAt: '2023-06-10 09:15:27',
        size: '458.7 MB',
        type: 'manual',
        status: 'success',
        content: ['database', 'models', 'config', 'logs']
      },
      {
        id: '5',
        name: '每周自动备份-202306-1',
        createdAt: '2023-06-04 03:00:00',
        size: '145.3 MB',
        type: 'auto',
        status: 'success',
        content: ['database', 'config']
      },
      {
        id: '6',
        name: '测试备份',
        createdAt: '2023-06-01 11:20:35',
        size: '120.0 MB',
        type: 'manual',
        status: 'failed',
        content: ['database']
      },
      {
        id: '7',
        name: '正在创建的备份',
        createdAt: '2023-06-16 10:25:12',
        size: '进行中',
        type: 'manual',
        status: 'processing',
        content: ['database', 'models', 'config', 'logs']
      }
    ]
    
    // 计算总条数
    pagination.total = mockData.length
    
    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    backupList.value = mockData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 刷新备份列表
const refreshBackupList = () => {
  fetchBackupList()
  
  ElMessage({
    message: '备份列表已刷新',
    type: 'success'
  })
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchBackupList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchBackupList()
}

// 保存备份配置
const saveBackupConfig = () => {
  // 在真实环境中这里会调用API
  ElMessage({
    message: '备份配置保存成功',
    type: 'success'
  })
}

// 创建备份
const createBackup = () => {
  // 重置新建备份表单
  newBackupForm.name = `手动备份-${new Date().toISOString().split('T')[0].replace(/-/g, '')}`
  newBackupForm.content = ['database']
  newBackupForm.description = ''
  
  backupDialogVisible.value = true
}

// 确认创建备份
const confirmCreateBackup = () => {
  if (!newBackupForm.name) {
    ElMessage.error('请输入备份名称')
    return
  }
  
  if (newBackupForm.content.length === 0) {
    ElMessage.error('请选择至少一项备份内容')
    return
  }
  
  // 关闭对话框
  backupDialogVisible.value = false
  
  // 显示正在创建备份的提示
  ElMessage({
    message: '正在创建备份，请稍候...',
    type: 'info'
  })
  
  // 模拟API请求延迟
  setTimeout(() => {
    ElMessage({
      message: '备份创建成功',
      type: 'success'
    })
    
    // 刷新备份列表
    fetchBackupList()
  }, 1500)
}

// 下载备份
const downloadBackup = (backup) => {
  ElMessage({
    message: `正在准备下载备份"${backup.name}"...`,
    type: 'info'
  })
  
  // 模拟下载延迟
  setTimeout(() => {
    ElMessage({
      message: `备份"${backup.name}"下载成功`,
      type: 'success'
    })
  }, 1000)
}

// 还原备份
const restoreBackup = (backup) => {
  // 设置当前备份对象
  Object.assign(currentBackup, backup)
  
  // 打开还原确认对话框
  restoreDialogVisible.value = true
}

// 确认还原
const confirmRestore = () => {
  // 关闭对话框
  restoreDialogVisible.value = false
  
  // 显示正在还原的提示
  ElMessage({
    message: '正在还原数据，请稍候...',
    type: 'info'
  })
  
  // 模拟API请求延迟
  setTimeout(() => {
    ElMessage({
      message: '数据还原成功，系统将在5秒后自动刷新',
      type: 'success'
    })
    
    // 模拟页面刷新
    setTimeout(() => {
      ElMessage({
        message: '页面刷新模拟：系统已完成还原',
        type: 'success'
      })
    }, 5000)
  }, 2000)
}

// 删除备份
const deleteBackup = (backup) => {
  ElMessageBox.confirm(`确定要删除备份"${backup.name}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 在真实环境中这里会调用API
    const index = backupList.value.findIndex(item => item.id === backup.id)
    if (index !== -1) {
      backupList.value.splice(index, 1)
      
      ElMessage({
        message: `备份"${backup.name}"已删除`,
        type: 'success'
      })
      
      // 更新总数
      pagination.total--
    }
  }).catch(() => {})
}

// 处理文件上传
const handleFileChange = (file) => {
  if (file) {
    selectedFile.value = file
    ElMessage({
      message: `已选择文件: ${file.name}`,
      type: 'success'
    })
  }
}

// 从文件还原
const restoreFromFile = () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择备份文件')
    return
  }
  
  ElMessageBox.confirm('确定要从选择的文件还原系统数据吗？此操作不可逆！', '警告', {
    confirmButtonText: '确定还原',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 显示正在还原的提示
    ElMessage({
      message: '正在从文件还原数据，请稍候...',
      type: 'info'
    })
    
    // 模拟API请求延迟
    setTimeout(() => {
      ElMessage({
        message: '数据还原成功，系统将在5秒后自动刷新',
        type: 'success'
      })
      
      // 清除选择的文件
      selectedFile.value = null
      
      // 模拟页面刷新
      setTimeout(() => {
        ElMessage({
          message: '页面刷新模拟：系统已完成还原',
          type: 'success'
        })
      }, 5000)
    }, 2000)
  }).catch(() => {})
}

// 获取备份类型标签
const getBackupTypeTag = (type) => {
  return type === 'auto' ? 'info' : 'primary'
}

// 获取备份类型名称
const getBackupTypeName = (type) => {
  return type === 'auto' ? '自动备份' : '手动备份'
}

// 获取备份内容描述
const getBackupContent = (backup) => {
  if (!backup || !backup.content) return ''
  
  const contentMap = {
    database: '数据库',
    models: '模型文件',
    config: '系统配置',
    logs: '系统日志'
  }
  
  return backup.content.map(item => contentMap[item] || item).join('、')
}

// 生命周期钩子
onMounted(() => {
  fetchBackupList()
})
</script>

<style lang="scss" scoped>
.backup-restore-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .backup-config-card {
    margin-bottom: 20px;
  }
  
  .backup-list-card {
    margin-bottom: 20px;
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .restore-card {
    .upload-area {
      margin-bottom: 20px;
      
      .upload-component {
        :deep(.el-upload) {
          width: 100%;
        }
        
        :deep(.el-upload-dragger) {
          width: 100%;
          height: 200px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      }
      
      .upload-text {
        margin: 10px 0;
        
        em {
          color: #409EFF;
          font-style: normal;
          cursor: pointer;
        }
      }
      
      .upload-hint {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .restore-actions {
      display: flex;
      align-items: center;
      gap: 20px;
    }
  }
  
  .restore-warning {
    .restore-detail {
      margin-top: 20px;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 4px;
      
      p {
        margin: 8px 0;
      }
    }
  }
}
</style> 